

import { defineStore } from 'pinia';
import { userApi } from '@/utils/userApi/index';
export const useUserStore = defineStore('user', {
	state: () => {
		return {
			openId: '',
			token: '',
			userInfo: {} as any,
		};
	},
	getters: {
		isLogin() : boolean {
			if (this.openId && this.token) {
				return true;
			}
			return false;
		},
		isDebug() : boolean {
			return true || this.getUserDesc.nickName == "测试";
		},
		getUserDesc() : UserDesc {
			const nickName = uni.getStorageSync('nickName');
			const avatar = uni.getStorageSync('avatar');
			return {
				nickName: nickName,
				avatar: avatar,
			};
		},
	},
	actions: {
		setUserDesc(data : UserDesc) {
			uni.setStorageSync('nickName', data.nickName);
			uni.setStorageSync('avatar', data.avatar);
		},
		setOpenId(data : string) {
			this.openId = data;
		},
		setUserInfo(data : any) {
			this.userInfo = data;
		},
		setToken(data : string) {
			this.token = data;
		},
		clearToken() {
			this.token = '';
		},
		async loginAsync() {//登录，用于启动时调用
			try {
				const res = await userApi.login();
				this.setToken(res);
				return Promise.resolve(res)
			} catch (error) {
				console.log('登录失败',error);
				return Promise.reject(error);
			}
		}
	},
});

export interface UserDesc extends Object {
	nickName ?: string,
	avatar ?: string,
}